<template>
  <el-dialog
    :model-value="visible"
    :title="comment ? '编辑评论' : '添加评论'"
    width="600px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="评论内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="6"
          placeholder="请输入评论内容"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="附件" prop="attachments">
        <el-upload
          ref="uploadRef"
          :file-list="fileList"
          :auto-upload="false"
          :limit="3"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          drag
          multiple
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              支持 jpg/png/gif/pdf/doc/docx 文件，且不超过 5MB
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item label="是否公开" prop="isPublic">
        <el-switch
          v-model="form.isPublic"
          active-text="公开"
          inactive-text="内部"
        />
        <span class="form-tip">公开评论客户可见，内部评论仅内部人员可见</span>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'CommentDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    ticketId: {
      type: [String, Number],
      default: null
    },
    comment: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const formRef = ref()
    const uploadRef = ref()
    const submitting = ref(false)
    const fileList = ref([])

    // 表单数据
    const form = reactive({
      content: '',
      attachments: [],
      isPublic: true
    })

    // 表单验证规则
    const rules = {
      content: [
        { required: true, message: '请输入评论内容', trigger: 'blur' },
        { min: 5, max: 500, message: '评论长度在 5 到 500 个字符', trigger: 'blur' }
      ]
    }

    // 监听comment变化，用于编辑模式
    watch(() => props.comment, (newComment) => {
      if (newComment) {
        Object.assign(form, {
          content: newComment.content || '',
          attachments: newComment.attachments || [],
          isPublic: newComment.isPublic !== false
        })
        
        // 设置文件列表
        fileList.value = (newComment.attachments || []).map((file, index) => ({
          name: file.name || `附件${index + 1}`,
          url: file.url,
          uid: file.id || index
        }))
      }
    }, { immediate: true })

    // 监听对话框显示状态，重置表单
    watch(() => props.visible, (visible) => {
      if (visible && !props.comment) {
        resetForm()
      }
    })

    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        content: '',
        attachments: [],
        isPublic: true
      })
      fileList.value = []
      formRef.value?.clearValidate()
    }

    // 文件上传相关方法
    const handleExceed = (files, fileList) => {
      ElMessage.warning(`最多只能上传 3 个文件，当前选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    }

    const beforeUpload = (file) => {
      const isValidType = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isValidType) {
        ElMessage.error('只能上传 jpg/png/gif/pdf/doc/docx 格式的文件!')
        return false
      }
      if (!isLt5M) {
        ElMessage.error('上传文件大小不能超过 5MB!')
        return false
      }
      return true
    }

    const handleFileChange = (file, fileList) => {
      // 文件选择变化时的处理
    }

    const handleFileRemove = (file, fileList) => {
      // 文件移除时的处理
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        submitting.value = true

        // 准备提交数据
        const submitData = {
          ...form,
          ticketId: props.ticketId,
          attachments: fileList.value.map(file => ({
            name: file.name,
            url: file.url || file.raw,
            size: file.size,
            type: file.raw?.type || 'unknown'
          }))
        }

        if (props.comment) {
          // 编辑评论
          await updateComment(props.comment.id, submitData)
          ElMessage.success('评论更新成功！')
        } else {
          // 创建评论
          await createComment(submitData)
          ElMessage.success('评论添加成功！')
        }

        emit('success')
        emit('update:visible', false)
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败：' + (error.message || '未知错误'))
      } finally {
        submitting.value = false
      }
    }

    // 创建评论
    const createComment = async (data) => {
      // 这里应该调用API创建评论
      console.log('创建评论:', data)
      return new Promise(resolve => setTimeout(resolve, 1000))
    }

    // 更新评论
    const updateComment = async (commentId, data) => {
      // 这里应该调用API更新评论
      console.log('更新评论:', commentId, data)
      return new Promise(resolve => setTimeout(resolve, 1000))
    }

    // 取消操作
    const handleCancel = () => {
      emit('update:visible', false)
    }

    return {
      formRef,
      uploadRef,
      submitting,
      fileList,
      form,
      rules,
      handleExceed,
      beforeUpload,
      handleFileChange,
      handleFileRemove,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style scoped>
.form-tip {
  margin-left: 12px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>
